package com.nets.server;

import com.nets.decoder.PacketDecoder;
import com.nets.encoder.PacketEncoder;
import com.nets.handler.PacketHandler;
import com.nets.pool.ServerPool;
import com.nets.util.LogUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;

/**
 * @author sig
 * @since 2016/9/17
 */
public class Server {
    private int port;
    private EventLoopGroup boss;
    private EventLoopGroup worker;

    public Server(int port) {
        this.port = port;
        startup();
    }

    public void startup() {
        boss = new NioEventLoopGroup();
        worker = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_SNDBUF, 128 * 1024)
                .option(ChannelOption.SO_RCVBUF, 128 * 1024)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer() {

                    @Override
                    protected void initChannel(Channel channel)
                            throws Exception {
                        channel.pipeline()
                                .addLast(new LengthFieldBasedFrameDecoder(
                                        1024 * 1024, 0, 4, 0, 4))
                                .addLast("serverPacketDecoder", new PacketDecoder())
                                .addLast("serverPacketHandler", new PacketHandler())
                                .addLast(new LengthFieldPrepender(4))
                                .addLast("serverPacketEncoder", new PacketEncoder());
                    }
                });

        try {
            bootstrap.bind(port).sync();
            LogUtil.console.info("The server has been launched.");
            ServerPool.startupFinish = true;
        } catch (Exception e) {
            LogUtil.console.error(e.getMessage(), e);
            shutdown();
        }
    }

    public void shutdown() {
        if (null != worker) worker.shutdownGracefully();
        if (null != boss) boss.shutdownGracefully();
    }
}
